package threaduse;

/**
 * @author DCSGO
 * @version 1.0
 * 线程使用案例-实现Runnable接口
 * 编写程序，该程序可以每隔1秒在输出hi
 * 当输出 4 次后，自动退出。使用Runnable接口
 */
public class Thread02 {
    public static void main(String[] args) {
        Say say = new Say();
        //Runnable 本身没有 start 方法
        //因此我们必须借助 Thread 来实现多线程(静态代理模式)
        Thread thread = new Thread(say);
        thread.start();
        //Say Thread: Thread-0
        //hi 0
        //hi 1
        //hi 2
        //hi 3
    }
}

class Say implements Runnable {

    @Override
    public void run() {
        System.out.println("Say Thread: " + Thread.currentThread().getName());

        int cnt = 0;
        while (cnt < 4) {
            System.out.println("hi " + cnt);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            cnt++;
        }
    }
}

//下面演示 Runnable 与 Thread 静态代理模式
class Animal {
    public static void main(String[] args) {
        Chicken chicken = new Chicken();
        ThreadProxy threadProxy = new ThreadProxy(chicken);
        threadProxy.start();
        //小鸡咕咕叫~
    }
}

class Chicken extends Animal implements Runnable {
    @Override
    public void run() {
        System.out.println("小鸡咕咕叫~");
    }
}

class ThreadProxy implements Runnable {
    Runnable target;

    @Override
    public void run() {
        if (target != null) {
            target.run();//动态绑定
        }
    }

    ThreadProxy(Runnable target) {
        this.target = target;
    }

    public void start() {
        start0();
    }

    public void start0() {
        //...创建线程
        run();
    }
}